package com.farewell.blog.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.farewell.blog.entity.QueryBean;
import com.farewell.blog.entity.SearchBlog;
import com.farewell.blog.mapper.BlogMapper;
import com.farewell.blog.pojo.Blog;
import com.farewell.blog.service.BlogService;
import com.farewell.blog.utils.MarkdownUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author Farewell
 * @date 2021/2/8
 */
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class BlogServiceImpl implements BlogService {
    @Autowired
    private BlogMapper blogMapper;


    @Override
    public void updateViews(Blog blog) {
        blogMapper.updateById(blog);
    }

    @Override
    public Page<Blog> listBlogByTypeId(QueryBean queryBean) {
        Page<Blog> pageData = new Page<>(queryBean.getCurrentPage(), queryBean.getPageSize());
        List<Blog> blogList = blogMapper.listBlogByTypeId(pageData, Long.parseLong(queryBean.getQueryString()));
        pageData.setRecords(blogList);
        return pageData;
    }

    @Override
    public List<Blog> getBlogListByTypeId(Long typeId) {
        EntityWrapper<Blog> wrapper = new EntityWrapper<>();
        wrapper.eq("type_id", typeId);
        return blogMapper.selectList(wrapper);
    }

    @Override
    public Blog getBlogById(Long id) {
        Blog blog = blogMapper.getBlogById(id);
        return blog;
    }

    @Override
    public Page<Blog> getBlogsBySearch(QueryBean queryBean, SearchBlog searchBlog) {
        Page<Blog> pageData = new Page<>(queryBean.getCurrentPage(), queryBean.getPageSize());
        List<Blog> blogList = blogMapper.getBlogsBySearch(pageData, searchBlog);
        pageData.setRecords(blogList);
        return pageData;
    }

    @Override
    public Page<Blog> listBlog(QueryBean queryBean) {
        Page<Blog> pageData = new Page<>(queryBean.getCurrentPage(), queryBean.getPageSize());
        List<Blog> blogList = blogMapper.getAllBlog(pageData);
        pageData.setRecords(blogList);
        return pageData;
    }

    @Override
    public void saveBlog(Blog blog) {
        blog.setCreateTime(new Date());
        blog.setUpdateTime(new Date());
        blogMapper.insert(blog);
    }

    @Override
    public void updateBlog(Blog blog) {
        blog.setUpdateTime(new Date());
        blogMapper.updateById(blog);
    }

    @Override
    public Blog getBlog(Blog blog) {
        return blogMapper.selectOne(blog);
    }

    @Override
    public void deleteBlog(Long id) {
        blogMapper.deleteById(id);
    }
}
